package com.medical.data.utils;

import cn.hutool.core.util.IdUtil;
import com.medical.data.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Component
@Slf4j
public class FileUtils {


    @Value("${upload.file-addr}")
    private  String fileAddr;

    @Value("${upload.url}")
    private String baseUrl;

    /**
     * 上传图片
     * @param file 文件
     * @param name 要上传到哪个文件夹里
     * @return
     */
    public String uploadImage(MultipartFile file,String name) {
        String filename = file.getOriginalFilename();
        String uuid = IdUtil.simpleUUID().toString();
        String newFileAddr = fileAddr +name+"/";
        String fileName = uuid+filename.substring(filename.lastIndexOf("."));
        File fileP = new File(newFileAddr);
        if (!fileP.isDirectory()) {
            //递归生成文件夹
            fileP.mkdirs();
        }
//        File file1 = FileUtil.touch(addr);
        log.info("=======>{}",fileP.getPath());
        try {
            InputStream inputStream = file.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(new File(fileP, fileName));
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 从输入流读取数据到缓冲区
            int data;
            while ((data = inputStream.read()) != -1) {
                bufferedOutputStream.write(data);
            }
            bufferedOutputStream.flush();
            inputStream.close();
            bufferedOutputStream.close();
        } catch (IOException e) {
            throw new MyException(ResultCode.ERROR.getCode(), "文件上传失败");
        }
        log.info("==========>{}",file.getOriginalFilename());
        String url =  baseUrl +name+"/"+ uuid+filename.substring(filename.lastIndexOf("."));
        log.info("url=========>{}",url);
        return url;
    }




}
